#include "option.h"
#include "stddef.h"
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include "common.h"

option_t g_option;

static int g_argc;
static char** g_argv;

static int has_arg(const char* arg)
{
    for (int i = 1; i < g_argc; ++i)
    {
        if (strcmp(g_argv[i], arg) == 0)
            return i;
    }
    return 0;
}

static const char* get_of_arg(const char* arg)
{
    int index = has_arg(arg);
    if (index > 0 && index + 1 < g_argc) {
        return g_argv[index + 1];
    }
    return NULL;
}

static char* get_file_name()
{
    for (int i = 1; i < g_argc; ++i)
    {
        if (g_argv[i][0] == '-') {
            if (g_argv[i][1] == '-')
                ++i;
            else
                continue;
        }
        return g_argv[i];
    }
    return NULL;
}

void init_option(int argc, char** argv)
{
    g_argc = argc;
    g_argv = argv;
}

void parse_option(int argc, char** argv)
{
    const char* arg = NULL;
	memset(&g_option, 0, sizeof(g_option));
    init_option(argc, argv);
    
    if (has_arg("--print-cmd")) {
        // system("pwd");
        for (int i = 0; i < argc; ++i)
        {
            printf(" %s", argv[i]);
        }
        printf("\n");
    }
    
    g_option.slash_as_comment = true;
    g_option.sharp_as_comment = true;
    g_option.dump_token = has_arg("--dump-token") != 0;
    g_option.dump_ast = has_arg("--dump-ast") != 0;
    g_option.dump_expr = has_arg("--dump-expr") != 0;
    g_option.dump_ref = has_arg("--dump-ref") != 0;
    g_option.io_mode = has_arg("-io") != 0;
    g_option.token_only = has_arg("--token-only") != 0;
    g_option.debug = has_arg("-d") != 0;
    g_option.debug_expr = has_arg("-dd") != 0;
    g_option.filename = get_file_name();
    if (str_end_of(g_option.filename, ".c")
        || str_end_of(g_option.filename, ".h")
        || str_end_of(g_option.filename, ".cpp")
        || str_end_of(g_option.filename, ".cxx")
        || str_end_of(g_option.filename, ".hpp")
        || str_end_of(g_option.filename, ".p4")
    ) {
        g_option.sharp_as_comment = false;
        g_option.decl_first= true;
    }
    arg = get_of_arg("--start");
    if (arg) {
        g_option.start = atoi(arg);
    }
    arg = get_of_arg("--count");
    if (arg) {
        g_option.end = g_option.start + atoi(arg);
    } else {
		g_option.end = 0x7fffffff;
	}
}